#ifndef MyController_hpp
#define MyController_hpp

#include "../dto/DTOs.h"

#include "oatpp-websocket/Handshaker.hpp"
#include "oatpp/macro/codegen.hpp"
#include "oatpp/macro/component.hpp"
#include "oatpp/web/server/api/ApiController.hpp"
#include "../Mysqlutil/test.h"
#include <cstddef>
#include <cstring>
#include <iostream>
#include <string>
// #include "oatpp/macro/component.hpp"
// #include "oatpp/base/Environment.hpp"
#include OATPP_CODEGEN_BEGIN(ApiController) //<-- Begin Codegen
int stuid = 0;
/**
 * Sample Api Controller.
 */

class MyController : public oatpp::web::server::api::ApiController {
private:
  OATPP_COMPONENT(std::shared_ptr<oatpp::network::ConnectionHandler>,
                  websocketConnectionHandler, "websocket");

public:
  /**
   * Constructor with object mapper.
   * @param apiContentMappers - mappers used to serialize/deserialize DTOs.
   */
  MyController(OATPP_COMPONENT(
      std::shared_ptr<oatpp::web::mime::ContentMappers>, apiContentMappers))
      : oatpp::web::server::api::ApiController(apiContentMappers) {}

public:
  ADD_CORS(login, "*", "*")
  ENDPOINT("POST", "/login", login, BODY_DTO(Object<MyDto>, userDto)) {
    MyDto *user = userDto.get();

    char condition[1024];
    sprintf(condition, " WHERE stuName = '%s' AND password = '%s';",
            user->name.getValue({}).c_str(),
            user->password.getValue({}).c_str());
    vector<Student> ret = StudentManager::GetInstance()->queryStu(condition);
    for (auto &it : ret) {
      std::cout << " ";
      cout << it.stuId << " " << it.stuName << " " << it.className
           << it.password << endl;
    }
    if (!ret.empty()) {
      std::cout << "response" << std::endl;
      return createResponse(Status::CODE_200, "OK");
    }
    return createResponse(Status::CODE_401, "Unauthorized");
  }
  ADD_CORS(reg, "*", "*")
  ENDPOINT("POST", "/reg", reg, BODY_DTO(Object<MyDto>, userDto)) {
    MyDto *user = userDto.get();
    char condition[1024];
    sprintf(condition, ";");
    vector<Student> ret = StudentManager::GetInstance()->queryStu(condition);
    for (auto &it : ret) {
      stuid= it.stuId;
    }
    int id = stuid++;

    Student stu{id, user->name.getValue({}), "风雨无阻",
                user->password.getValue({})};
    StudentManager::GetInstance()->insertStu(stu);
    return createResponse(Status::CODE_200, "OK");
  }

  ADD_CORS(chat, "*", "*")
  ENDPOINT("GET", "/chat", chat,
           REQUEST(std::shared_ptr<IncomingRequest>, request)) {
          
    auto response = oatpp::websocket::Handshaker::serversideHandshake(
        request->getHeaders(), websocketConnectionHandler);
    auto parameters =
        std::make_shared<oatpp::network::ConnectionHandler::ParameterMap>();
    (*parameters)["id"] = request->getQueryParameter("id");
    response->setConnectionUpgradeParameters(parameters);
    return response;
  }
};

#include OATPP_CODEGEN_END(ApiController) //<-- End Codegen

#endif /* MyController_hpp */
